package com.zhenyi.zhaozheng.web;

import java.util.Date;

import org.hashids.Hashids;

import com.cjw.model.DBMap;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.zhaozheng.common.model.ZzActivity;
import com.zhaozheng.common.model.ZzEnroll;
import com.zhenyi.core.ZIndexController;

public class ActivityController extends ZIndexController {

	protected Hashids hashids = new Hashids("zhaozheng", 8);

	/**
	 * 提交报名
	 */
	public void enroll() {
		String code = getPara("code");
		String name = getPara("name");
		String mobile = getPara("mobile");
		String remark = getPara("remark");
		if (StrKit.isBlank(code)) {
			renderFailure("activity code is required");
			return;
		}
		Long activityId = null;
		try {
			activityId = hashids.decode(code)[0];
		} catch (Exception e) {
			LogKit.warn("zz activity code decode erorr: " + code);
			e.printStackTrace();
		}
		ZzActivity activity = ZzActivity.dao.findById(activityId);
		if (activity == null) {
			renderError(404);
			return;
		}
		DBMap map = new DBMap();
		map.put("activityId", activityId);
		map.put("mobile", mobile);
		ZzEnroll enroll = ZzEnroll.dao.searchFirst(map);
		if (enroll != null) {
			renderFailure(500, "该电话号码已经报过名了");
			return;
		}
		enroll = new ZzEnroll();
		enroll.setName(name);
		enroll.setMobile(mobile);
		enroll.setRemark(remark);
		enroll.setActivityId(activityId);
		enroll.setStatus(0);
		renderFlag(enroll.save());
	}

	/**
	 * 参加活动
	 */
	public void attend() {
		String code = getPara("code");
		// String name = getPara("name");
		String mobile = getPara("mobile");

		if (StrKit.isBlank(code)) {
			renderFailure("activity code is required");
			return;
		}
		Long activityId = null;
		try {
			activityId = hashids.decode(code)[0];
		} catch (Exception e) {
			LogKit.warn("zz activity code decode erorr: " + code);
			e.printStackTrace();
		}
		ZzActivity activity = ZzActivity.dao.findById(activityId);
		if (activity == null) {
			renderError(404);
			return;
		}

		DBMap map = new DBMap();
		map.put("activityId", activityId);
		// map.put("name", name);
		map.put("mobile", mobile);
		ZzEnroll info = ZzEnroll.dao.searchFirst(map);
		if (info == null) {
			renderFailure(500, "你没有报名此活动");
			return;
		}
		if (info.getStatus().equals(1)) {
			renderFailure(500, "你已经参加了此活动");
			return;
		}
		info.setStatus(1);
		info.setAttendTime(new Date());
		renderFlag(info.update());
	}

}
